<template>
  <div class="course-container">
    <!-- 搜索区域 -->
    <div class="search-card">
      <el-form :inline="true" :model="courseSearchModel" class="demo-form-inline" ref="courseSearchForm">
        <el-form-item label="课程名称：" prop="name">
          <el-input
              v-model="courseSearchModel.courseName"
              placeholder="请输入课程名称"
              :prefix-icon="Search"
              class="search-input"
              clearable
              @clear="reset"
          />
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <el-button type="primary" :icon="CirclePlus" @click="add" class="action-btn add-btn">新增</el-button>
      <el-button type="primary" :icon="Search" @click="searchAll()" class="action-btn search-btn">查询</el-button>
      <el-button type="primary" :icon="RefreshRight" @click="reset" class="action-btn reset-btn">重置</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
          :data="courses"
          height="100%"
          style="width: 100%"
          stripe
          border
          class="table-grid"
          @row-click="tblRowClick"
          ref="tblRef"
          :row-class-name="tableRowClassName"
          v-loading="loading"
      >
        <el-table-column type="selection" width="100" align="center"/>
        <el-table-column prop="courseId" label="课程ID" width="125" fixed/>
        <el-table-column prop="courseName" label="课程名称" width="180" fixed/>
        <el-table-column prop="type" label="课程类型" width="100">
          <template #default="scope">
            <el-tag
                :type="scope.row.type === '初级' ? 'info' : scope.row.type === '中级' ? 'warning' : 'danger'"
                size="small"
            >
              {{ scope.row.type}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="coachName" label="教练" width="160"/>
        <el-table-column prop="roomName" label="教室" width="160"/>
        <el-table-column prop="schedule" label="上课时间" width="200"/>
        <el-table-column prop="duration" label="时长（分钟）" width="160"/>
        <el-table-column prop="maxStudent" label="容量" width="100"/>
        <el-table-column prop="contain" label="已预约" width="100"/>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click.stop="edit(scope.row)" class="table-btn edit">编辑</el-button>
            <el-button type="danger" size="small" @click.stop="removeRow(scope.row)" class="table-btn delete">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="coursePi.pageNo"
          v-model:page-size="coursePi.pageSize"
          :page-sizes="[10, 20, 30, 40, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="coursePi.total"
          class="course-pi"
          @change="coursePiChange"
          background=true
      />
    </div>

    <!-- 添加/修改对话框 -->
    <el-dialog
        v-model="courseDlgShow"
        :title="courseDlgTitle"
        width="600px"
        :close-on-click-modal="false"
        draggable
        show-close
        align-center
        @close="resetCourseForm"
        class="course-dialog"
    >
      <el-form
          label-width="100"
          label-position="right"
          :model="courseModel"
          ref="courseForm"
          :rules="rules"
          class="course-form"
      >
        <el-form-item label="课程名称" prop="courseName">
          <el-input placeholder="请输入课程名称" v-model="courseModel.courseName"></el-input>
        </el-form-item>

        <el-form-item label="教练" prop="coachId">
          <el-select v-model="courseModel.coachId" placeholder="请选择教练" class="w-100">
            <el-option
                v-for="coach in enabledCoaches"
                :key="coach.id"
                :label="coach.name"
                :value="coach.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="教室" prop="roomId">
          <el-select v-model="courseModel.roomId" placeholder="请选择教室" class="w-100" @focus="checkRoomStatus"
                     @change="handleRoomChange">
            <el-option
                v-for="room in enabledRooms"
                :key="room.id"
                :label="room.name"
                :value="room.id"
            >
              <span>{{ room.name }}</span>
              <el-tag
                  :type="room.status === 1 ? 'success' : 'danger'"
                  size="small"
                  style="margin-left: 10px;"
              >
                {{ room.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </el-option>
          </el-select>
          <div v-if="disabledRooms.length > 0" class="disabled-rooms-tip">
            <el-alert
                :title="`有 ${disabledRooms.length} 个教室处于禁用状态，无法选择`"
                type="warning"
                show-icon
                :closable="false"
                style="margin-top: 10px;"
            />
          </div>
        </el-form-item>
        <el-form-item label="课程类型" prop="type">
          <el-select v-model="courseModel.type" placeholder="请选择课程等级" style="width: 240px">
            <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时长(分钟)" prop="duration">
          <el-input placeholder="请输入时长" v-model="courseModel.duration"></el-input>
        </el-form-item>
        <el-form-item label="上课时间" prop="schedule">
          <el-date-picker
              v-model="courseModel.schedule"
              type="datetime"
              placeholder="请选择上课时间"
              style="width: 100%"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="doSubmit" class="dialog-btn confirm">确定</el-button>
          <el-button @click="courseDlgShow=false" class="dialog-btn cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.course-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 搜索区域样式 */
.search-card {
  background: #fff;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 15px;
}

.search-input {
  transition: all 0.3s ease;
  width: 240px;
}

.search-input:focus-within {
  box-shadow: 0 0 0 2px rgba(145, 163, 255, 0.2);
}

/* 操作按钮区域 */
.action-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.action-btn {
  transition: all 0.2s ease;
  border-radius: 4px;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.add-btn {
  background-color: #409eff;
}

.search-btn {
  background-color: #1890ff;
}

.reset-btn {
  background-color: #909399;
}

/* 表格区域样式 */
.table-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  margin-bottom: 15px;
}

.table-grid {
  margin-top: 0;
  border: none;
}

.el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
}

.el-table tr:hover > td {
  background-color: #f0f7ff !important;
}

.tableRowClassName {
  transition: background-color 0.2s ease;
}

/* 表格操作按钮 */
.table-btn {
  border-radius: 4px;
  margin: 0 3px;
  transition: all 0.2s ease;
}

.table-btn.edit {
  background-color: #409eff;
  border-color: #409eff;
}

.table-btn.delete {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.table-btn:hover {
  transform: scale(1.05);
}

/* 分页区域 */
.pagination-container {
  background: #fff;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.course-pi {
  margin-top: 0;
  text-align: right;
}

/* 对话框样式 */
.course-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.course-form {
  margin-top: 15px;
}

.w-100 {
  width: 100%;
}

/* 对话框按钮 */
.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.dialog-btn {
  width: 100px;
  transition: all 0.2s ease;
}

.dialog-btn.confirm {
  background-color: #409eff;
  border-color: #409eff;
}

.dialog-btn.cancel {
  background-color: #f5f5f5;
  color: #333;
}

.dialog-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 禁用教室提示 */
.disabled-rooms-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

/* 动画效果 */
.el-button, .el-input, .el-select, .el-date-picker, .el-table, .el-dialog {
  transition: all 0.2s ease-in-out;
}

.el-table__row {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(5px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>

<script setup>
import {onMounted, ref, reactive, toRaw, nextTick, computed} from "vue"
import api from "@/util/api"
import {CirclePlus, Delete, Edit, Plus, RefreshRight, Search} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {cloneDeep} from "lodash";

onMounted(async () => {
  searchAll();
  fetchCoaches();
  fetchRooms();
});

let courses = ref();
let loading = ref(false);
let coursePi = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
});

let courseSearchModel = ref({
  courseName: null
});

let courseSearchForm = ref();
let courseDlgTitle = ref("新增课程");
let courseDlgShow = ref(false);
let tblRef = ref();

let courseModel = ref({
  type: null,
  courseId: null,
  courseName: null,
  coachId: null,
  coachName: null,
  roomName: null,
  roomId: null,
  schedule: null,
  maxStudent: 20,
  duration: null
});

let coachList = ref([]);
let roomList = ref([]);
//计算在职教练
const enabledCoaches = computed(() => {
  return coachList.value.filter(coach => coach.status === 1);
})

// 计算属性：启用的教室
const enabledRooms = computed(() => {
  return roomList.value.filter(room => room.status === 1);
});

// 计算属性：禁用的教室
const disabledRooms = computed(() => {
  return roomList.value.filter(room => room.status !== 1);
});

const typeOptions = [
  {
    value: '初级',
    label: '初级',
  },
  {
    value: '中级',
    label: '中级',
  }, {
    value: '高级',
    label: '高级',
  }
];

let mode = "add";
let courseForm = ref();

// 表单校验规则
const rules = {
  courseName: [
    {required: true, message: '请输入课程名称', trigger: 'blur'}
  ],
  coachId: [
    {required: true, message: '请选择教练', trigger: 'blur'}
  ],
  roomId: [
    {required: true, message: '请选择教室', trigger: 'blur'},
    {validator: validateRoomStatus, trigger: 'change'}
  ],
  schedule: [
    {required: true, message: '请选择上课时间', trigger: 'blur'}
  ],
  duration: [
    {required: true, message: '请输入时长', trigger: 'blur'}
  ],
  type: [
    {required: true, message: '请选择课程类型', trigger: 'blur'}
  ]
};

// 教室状态校验器
function validateRoomStatus(rule, value, callback) {
  if (!value) {
    return callback(new Error('请选择教室'));
  }

  const selectedRoom = roomList.value.find(room => room.id === value);
  if (selectedRoom && selectedRoom.status !== 1) {
    return callback(new Error('选择的教室处于禁用状态，无法使用'));
  }
  callback();
}

//教室选择变化
function handleRoomChange(value) {
  if (value) {
    const room = roomList.value.find(r => r.id === value);
    if (room) {
      // 自动将教室容量赋值给课程容量
      courseModel.value.maxStudent = room.capacity;
    }
  }
}

//查询
async function searchAll(pageNo = 1, pageSize = 10) {
  loading.value = true;
  try {
    let params = toRaw(courseSearchModel.value);

    let resp = await api({
      url: "/course",
      method: "get",
      params: {
        pageNo,
        pageSize,
        ...params
      }
    });
    console.log(resp);
    courses.value = resp.data.records;
    coursePi.pageSize = resp.data.size;
    coursePi.total = resp.data.total;
    coursePi.pageNo = resp.data.current;
  } catch (e) {
    ElMessage.error("获取课程失败");
  } finally {
    loading.value = false;
  }
}

//页码变化
function coursePiChange(pageNo, pageSize) {
  searchAll(pageNo, pageSize);
}

//重置按钮
function reset() {
  courseSearchForm.value.resetFields();
  searchAll();
}

//点击行
function tblRowClick(row) {
  tblRef.value.toggleRowSelection(row);
}

// 用于表格行样式的回调函数，设置CSS类名
function tableRowClassName({row, rowIndex}) {
  return 'tableRowClassName';
}


async function removeByIds(ids) {
  try {
    await api({
      url: "/course",
      method: "delete",
      data: ids
    });
    ElMessage.success("删除成功")
    searchAll();
  } catch (e) {
    ElMessage({
      type: 'info',
      message: '删除失败',
    })
  }
}

function add() {
  courseDlgTitle.value = "新增课程";
  courseDlgShow.value = true;
  mode = "add";
  courseModel.value = {
    courseId: null,
    courseName: null,
    coachId: null,
    roomId: null,
    schedule: null,
    maxStudent: 20
  }
}

function doSubmit() {
  if (mode === "add") {
    submitAdd();
  } else {
    subEdit();
  }
}

//提交新增
function submitAdd() {
  courseForm.value.validate(async (valid) => {
    if (valid) {
      try {
        let params = toRaw(courseModel.value);
        await api({
          url: "/course",
          method: "post",
          data: params
        });
        courseDlgShow.value = false;
        searchAll();
        ElMessage.success("新增成功")
      } catch (e) {
        ElMessage.error(e.msg || "新增失败")
      }
    } else {
      ElMessage.error("请填写必填项")
    }
  })
}

//重置表单
function resetCourseForm() {
  courseForm.value.resetFields();
}

function edit(row) {
  courseDlgTitle.value = "编辑课程";
  courseDlgShow.value = true;
  mode = "edit";
  nextTick(() => {
    courseModel.value = cloneDeep(toRaw(row))
  })
}

//提交编辑
function subEdit() {
  courseForm.value.validate(async (valid) => {
    if (valid) {
      let params = toRaw(courseModel.value);
      try {
        let resp = await api({
          url: "/course",
          method: "put",
          data: params
        });
        if (resp.success) {
          courseDlgShow.value = false;
          searchAll(coursePi.pageNo, coursePi.pageSize);
          ElMessage.success("修改成功");
        } else {
          ElMessage.error(resp.msg || "修改失败")
        }
      } catch (e) {
        ElMessage.error(e.msg || "修改失败")
      }
    } else {
      ElMessage.error("请填写必填项")
    }
  });
}

//删除行
function removeRow(row) {
  ElMessageBox.confirm(
      '是否确认删除',
      '警告',
      {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
      }
  ).then(() => {
    removeByIds([row.courseId]);
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除',
    })
  })
}

// 获取教练列表
const fetchCoaches = async () => {
  try {
    const res = await api.get("/coach");
    coachList.value = res.data.records;
  } catch (e) {
    ElMessage.error("获取教练列表失败");
  }
};

// 获取教室列表
const fetchRooms = async () => {
  try {
    const res = await api.get("/classroom/all");
    roomList.value = res.data;
    //console.log(res);
  } catch (e) {
    ElMessage.error("获取教室列表失败");
  }
};

// 检查教室状态（在教室选择框获得焦点时调用）
function checkRoomStatus() {
  if (disabledRooms.value.length > 0) {
    ElMessage.warning(`有 ${disabledRooms.value.length} 个教室处于禁用状态，无法选择`);
  }
}
</script>
